package com.example.pceb.controller;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pceb.entity.*;
import com.example.pceb.service.ChatMessageService;
import com.example.pceb.service.Impl.EnterPriseServiceImpl;
import com.example.pceb.service.Impl.ResumeSendService;
import com.example.pceb.service.Impl.ResumeServiceImpl;
import com.example.pceb.service.Impl.UserServiceImpl;
import com.example.pceb.service.RecruitService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Value;

//聊天室
@RestController
//@CrossOrigin(origins = "*")
@RequestMapping("/chat")
public class ChatMessageController {
    @Autowired
    private ChatMessageService chatMessageService;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private EnterPriseServiceImpl enterPriseServiceImpl;
    @Autowired
    private ResumeSendService resumeSendService;
    @Autowired
    private RecruitService recruitService;
    @Autowired
    private ResumeServiceImpl resumeServiceImpl;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;
    //保存消息
    @PostMapping("save")
    public boolean saveMessage(@RequestBody ChatMessage msg){
        return chatMessageService.save(msg);
    }

    // 查询历史消息（带已读状态）
    @GetMapping("history")
    public List<ChatMessage> getHistory(@RequestParam String user1, @RequestParam String user2) {
        return chatMessageService.lambdaQuery()
                .and(q -> q.eq(ChatMessage::getFromUser, user1).eq(ChatMessage::getToUser, user2)
                        .or()
                        .eq(ChatMessage::getFromUser, user2).eq(ChatMessage::getToUser, user1))
                .orderByAsc(ChatMessage::getSendTime)
                .list();
    }

    // 标记消息为已读
    @PostMapping("markRead")
    public boolean markRead(@RequestBody MarkReadRequest req) {
        // 将 fromUser 发给 toUser 的未读消息全部标记为已读
        return chatMessageService.lambdaUpdate()
                .eq(ChatMessage::getFromUser, req.fromUser)
                .eq(ChatMessage::getToUser, req.toUser)
                .eq(ChatMessage::getIsRead, 0)
                .set(ChatMessage::getIsRead, 1)
                .update();
    }

    //DTO
    public static class MarkReadRequest {
        public String fromUser;
        public String toUser;
    }

    //学生端用户列表为所有企业管理员
    @GetMapping("enterpriseUsers")
    public List<EnterpriseUserDTO> getEnterpriseUsers(@RequestParam String student){
        List<Enterprise> list= enterPriseServiceImpl.list(
                new QueryWrapper<Enterprise>().select("username","enterprise")
        );
        return list.stream().map(e->{
            EnterpriseUserDTO dto=new EnterpriseUserDTO();
            dto.setUsername(e.getUsername());
            dto.setEnterprise(e.getEnterprise());
            return dto;
        }).toList();
    }

    // DTO
    public static class EnterpriseUserDTO {
        private String username;
        private String enterprise;
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getEnterprise() { return enterprise; }
        public void setEnterprise(String enterprise) { this.enterprise = enterprise; }
    }

    //企业端获取用户列表
    @GetMapping("/studentUsers")
    public List<StudentUserDTO> getStudentUsers(@RequestParam String enterprise) {
        //先获取该用户对应的公司名
        Enterprise ent = enterPriseServiceImpl.getOne(
                new QueryWrapper<Enterprise>().eq("username", enterprise)
        );
        if (ent == null) {
            return Collections.emptyList();
        }
        String companyName = ent.getEnterprise();

        //在recruit表里根据公司名查这个公司发布的所有职位id
        List<Integer> recruitIds = recruitService.list(
                new QueryWrapper<Recruit>().eq("enterprise", companyName)
        ).stream().map(Recruit::getId).collect(Collectors.toList());

        if (recruitIds.isEmpty()) {
            return Collections.emptyList();
        }

        //根据职位id查resume_send表，获取向该公司发布的所有学生用户名
        List<ResumeSend> sends = resumeSendService.list(
                new QueryWrapper<ResumeSend>().in("recruit_id", recruitIds)
        );
        Set<String> studentUsernames = sends.stream()
                .map(ResumeSend::getUsername)
                .collect(Collectors.toSet());

        if (studentUsernames.isEmpty()) {
            return Collections.emptyList();
        }

        //根据用户名查resume表 ，获取学生真实姓名
        List<Resume> resumes = resumeServiceImpl.list(
                new QueryWrapper<Resume>().in("username", studentUsernames)
        );

        //返回真实姓名列表
        return resumes.stream()
                .map(r -> {
                    StudentUserDTO dto = new StudentUserDTO();
                    dto.setUsername(r.getUsername());
                    dto.setName(r.getName());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    //dto
    public static class StudentUserDTO {
        private String username;
        private String name;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    //上传文件
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
        ossClient.putObject(bucketName, filename, file.getInputStream());
        ossClient.shutdown();

        Map<String, Object> result = new HashMap<>();
        result.put("objectName", filename); // 关键：返回objectName
        return result;
    }

    // 生成带签名的临时访问链接
    @GetMapping("/oss/signUrl")
    public String getSignUrl(@RequestParam String objectName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 1小时
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
        req.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(req);
        ossClient.shutdown();
        return url.toString();
    }
}
